package com.chat.security.filter;

import com.chat.security.authentication.TokenAuthentication;
import com.chat.security.service.JwtTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationManager providerManager;
    @Autowired
    JwtTokenService tokenService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String bearerToken = request.getHeader("Authorization");
        String token = parseBearerToken(bearerToken);
        if (token == null) {
            filterChain.doFilter(request,response);
            return;
        }
        final Authentication authenticate = providerManager.authenticate(new TokenAuthentication(token,tokenService));

        final SecurityContext emptyContext = SecurityContextHolder.createEmptyContext();
        emptyContext.setAuthentication(authenticate);
        SecurityContextHolder.setContext(emptyContext);

        filterChain.doFilter(request,response);
    }

    private String parseBearerToken(String bearerToken) {
        if (bearerToken == null) {
            return null;
        }
        if (bearerToken.startsWith("Bearer ")) {
            return bearerToken.replace("Bearer ", "");
        }else {
            return null;
        }
    }
}
